let currentAudio = null;
let currentButton = null;
let currentProgressBar = null;
document.querySelectorAll('.play-pause-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
        const wrapper = btn.closest('.audio-wrapper');
        const progressBar = wrapper.querySelector('.progress-bar');
        const audioSrc = btn.getAttribute('data-src');

        // 处理其他音频播放中的情况
        if (currentAudio && currentButton !== btn) {
            currentAudio.pause();
            currentAudio.currentTime = 0;
            currentButton.textContent = '播放';
            currentProgressBar.value = 0;
        }

        // 创建或获取音频对象
        const audio = currentAudio === btn.audio ? currentAudio : createAudio(audioSrc, btn, progressBar);

        try {
            if (btn.textContent === '播放') {
                // 预加载并播放
                await audio.play();
                btn.textContent = '暂停';
                currentAudio = audio;
                currentButton = btn;
                currentProgressBar = progressBar;
            } else {
                audio.pause();
                btn.textContent = '播放';
            }
        } catch (error) {
            console.error('播放失败:', error);
            btn.textContent = '播放';
            progressBar.value = 0;
        }
    });
});

function createAudio(src, btn, progressBar) {
    const audio = new Audio();
    audio.src = src;
    audio.preload = 'auto'; // 优化预加载策略

    // 单次绑定事件（避免重复绑定）
    audio.addEventListener('timeupdate', () => {
        progressBar.value = (audio.currentTime / audio.duration) * 100 || 0;
    }, { once: true });

    audio.addEventListener('loadedmetadata', () => {
        progressBar.max = audio.duration;
        progressBar.value = 0;
    });

    audio.addEventListener('ended', () => {
        btn.textContent = '播放';
        progressBar.value = 0;
        currentAudio = null;
        currentButton = null;
        currentProgressBar = null;
    });

    audio.addEventListener('error', () => {
        btn.textContent = '播放';
        progressBar.value = 0;
        console.error('音频加载失败');
    });

    // 关联按钮和音频对象
    btn.audio = audio;
    return audio;
}

// 进度条点击跳转 
document.querySelectorAll('.progress-bar').forEach(bar => {
    bar.addEventListener('click', (e) => {
        const audio = bar.closest('.audio-wrapper').querySelector('audio');
        const rect = bar.getBoundingClientRect();
        const pos = (e.clientX - rect.left) / rect.width;
        audio.currentTime = pos * audio.duration;
        bar.value = pos * 100;
    });
});
